package cn.zf233.springsecurityjwt.config.open;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * Created by zf233 on 2021/7/12
 */
@Component("openAuthenticationProvider")
public class OpenAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private OpenDetailsService openDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String openId = authentication.getName();
        UserDetails user = openDetailsService.loadUserByUsername(openId);
        if (ObjectUtils.isEmpty(user)) {
            throw new BadCredentialsException("用户信息加载失败");
        }
        return new OpenAuthenticationToken(user, null);
    }
    
    @Override
    public boolean supports(Class<?> aClass) {
        return OpenAuthenticationToken.class.isAssignableFrom(aClass);
    }
}